package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.common.exception.BssException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @Classname RentStartTimeHandler
 * @Description 起租时间不能早于当前时间校验（补录单不做校验）
 * @Author zhang.song
 * @Date 2021-04-22 11:44
 */
@Service
public class RentStartTimeHandler extends AbstractAttrHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Override
    public void init(CommonAttrVO commonAttrVO) {

    }

    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        if (KiteStringUtils.isNotEmpty(value)) {
            // 订单性质（2：补录单），补录单的起租时间可以选择当前时间之前
            String orderNature = querySceneInstService.getCommonAttrValue(sceneInstId, LocalKeyConsts.ORDER_NATURE);
            if(!KiteStringUtils.isEqual(orderNature, "2")) {
                DateTimeFormatter dtf = null;
                if (value.length() == 10) {
                    dtf = DateTimeFormatter.ofPattern(DateFormatUtils.DATE_FORMAT);
                } else {
                    dtf = DateTimeFormatter.ofPattern(DateFormatUtils.DATE_TIME_FORMAT);
                }
                LocalDate targetDate = null;
                try {
                    targetDate = LocalDate.parse(value, dtf);
                } catch (Exception e) {
                    ErrorConsts.SYSTEM_ERROR.throwOut(e.getMessage());
                }
                // 小于当前时间
                LocalDate nowDate = LocalDate.now();
                if (nowDate.isAfter(targetDate)) {
                    BssException.throwOut("", "", "起租时间不能早于当前时间");
                }
            }
        }

        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }
}
